package com.zygame.sdk.view.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.AttributeSet;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.zygame.sdk.utils.log.LogHelper;

public class MyWebView extends WebView {
	private Context mContext;
	
	public static ValueCallback<Uri> mUploadMessage;
	public static int  FILECHOOSER_RESULTCODE = 1;
	
	
	public MyWebView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		initMyWebView(context);
	}

	public MyWebView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		initMyWebView(context);
	}

	public MyWebView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		initMyWebView(context);
	}

	private void initMyWebView(Context context) {
		// TODO Auto-generated method stub
		this.mContext = context;

		WebSettings settings = getSettings();

		settings.setJavaScriptEnabled(true);
		settings.setDomStorageEnabled(true);
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setSupportZoom(true);
		settings.setBuiltInZoomControls(true);
		settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

		// 自适应屏幕
		settings.setUseWideViewPort(true);
		settings.setLoadWithOverviewMode(true);

		this.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		this.setInitialScale(50);
		this.setHorizontalScrollbarOverlay(true);
		this.setHorizontalScrollBarEnabled(true);
		this.setWebViewClient(new MyWebViewClient());
		this.setWebChromeClient(new MyWebChromeClient(context));
		// this.setWebViewClient(client)
	}

	private class MyDownload implements DownloadListener {
		@Override
		public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
			// TODO Auto-generated method stub
			// new DownloadThread(url).start();
			Uri uri = Uri.parse(url);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			mContext.startActivity(intent);
		}
	}

	/**
	 * @ClassName: DownloadThread
	 * @author K
	 * @Description: TODO(下载线程)
	 * @date 2015-1-3 下午4:17:39
	 */
	private class DownloadThread extends Thread {
		private String mUrl;

		public DownloadThread(String url) {
			this.mUrl = url;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			try {
				URL url = new URL(mUrl);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setDoInput(true);
				connection.setDoOutput(true);

				InputStream ins = connection.getInputStream();
				FileOutputStream ops = null;

				File downloadFile;

				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
					downloadFile = Environment.getExternalStorageDirectory();

					File sdFile = new File(downloadFile, "65Down");
					ops = new FileOutputStream(sdFile);
				}
				byte[] b = new byte[6 * 1024];

				int len;

				while ((len = ins.read(b)) != -1) {
					if (ops != null) {
						ops.write(b, 0, len);
					}
				}
				if (ops != null) {
					ops.close();
				}
				if (ins != null) {
					ins.close();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	private class MyWebChromeClient extends WebChromeClient {
		private Context context;

		public MyWebChromeClient(Context context) {
			super();
			this.context = context;
		}

		public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
			// TODO Auto-generated method stub
			new AlertDialog.Builder(context).setMessage(message).setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					result.confirm();
				}
			}).setCancelable(false).create().show();
			return true;
		}
		
		

		@Override
		public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
			AlertDialog.Builder b = new AlertDialog.Builder(context);
			b.setTitle("Confirm");
			b.setMessage(message);
			b.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					result.confirm();
				}
			});
			b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					result.cancel();
				}
			});
			b.setCancelable(false);
			b.create();
			b.show();
			return true;
		};
		
		



		@Override
		public void onReceivedTitle(WebView view, String title) {
			// TODO Auto-generated method stub
			super.onReceivedTitle(view, title);
		}

		// For Android 3.0+
		public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
			mUploadMessage = uploadMsg;
			 select();
		}

		// For Android < 3.0
		public void openFileChooser(ValueCallback<Uri> uploadMsg) {
			openFileChooser(uploadMsg, "");
		}

		// For Android > 4.1.1
		public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
			openFileChooser(uploadMsg, acceptType);
		}

	}

	private class MyWebViewClient extends WebViewClient {
		/**
		 * load url 出错的回调(暂时没有用到);
		 */
		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			// TODO Auto-generated method stub
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub

			super.onPageStarted(view, url, favicon);
			LogHelper.i("sss","装载前 "+ url);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
			LogHelper.i("sss","装载后 "+ url);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			return super.shouldOverrideUrlLoading(view, url);
		}
	}

	/**
	 * 
	 * @ClassName: HttpCookie
	 * @author K
	 * @Description: TODO(同步cookie)
	 * @date 2015-1-3 下午4:54:12
	 */
	private class HttpCookie extends Thread {
		// HttpClient client = new DefaultHttpClient();
	}
	
//	AlertDialog.Builder builder = new Builder(mContext);
	
	protected final void select() {
		if (!checkSDcard())
			return;
//		String[] selectPicTypeStr = { "选择照片", "拍照" };
		String[] selectPicTypeStr = { "选择照片"};
		
		new AlertDialog.Builder(mContext).setItems(selectPicTypeStr, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				// 相机拍摄
				case 0:
					chosePic();
					break;
				// 手机相册
//				case 1:
////					openCarcme();
//					break;
				default:
					break;
				}
			}
		}).setCancelable(false).setNegativeButton("取消", new AlertDialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				MyWebView.mUploadMessage.onReceiveValue(null);
				MyWebView.mUploadMessage = null;
			}
		}).show();
	}
	
	/**
	 * 检查SD卡是否存在
	 * 
	 * @return
	 */
	public final boolean checkSDcard() {
		boolean flag = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
		if (!flag) {
			Toast.makeText(mContext, "请插入手机存储卡再使用本功能", Toast.LENGTH_SHORT).show();
		}
		return flag;
	}
	
	/**
	 * 本地相册选择图片
	 */
	private void chosePic() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		((Activity)mContext).startActivityForResult(Intent.createChooser(intent, "完成操作需要使用"), FILECHOOSER_RESULTCODE);
	}

}
